﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Mail;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace Altairis.MailToolkit.ListManager.Pages.Admin {
    public partial class ImportMembers : System.Web.UI.Page {

        protected void SubmitButton_Click(object sender, EventArgs e) {
            if (!this.IsValid) return;

            // Get list
            var listName = this.RouteData.Values["listname"] as string;
            var list = MailingListManager.Lists[listName];

            // Get e-mail addresses
            var lines = this.AddressListTextBox.Text.ToLower().Split(new string[] { Environment.NewLine }, StringSplitOptions.RemoveEmptyEntries);

            // Get base URL
            var baseUrl = new UriBuilder(this.Request.Url) { Path = "", Query = "" };

            // Try to force subscribe them
            int successCount = 0, skippedCount = 0, errorCount = 0;
            var skippedData = new List<string>();
            var errorData = new List<string>();
            foreach (var line in lines) {
                var address = TryParseMailAddress(line);
                if (address == null) {
                    // Invalid address
                    errorCount++;
                    errorData.Add(line);
                    continue;
                }

                // Subscribe
                bool r;
                if (this.ListSubscriptionType.SelectedValue.Equals("ASK")) {
                    r = list.Subscribe(address, baseUrl);
                }
                else {
                    r = list.SubscribeForce(address);
                }
                if (r) {
                    // Subscription succeeded
                    successCount++;
                }
                else {
                    // Subscription failed - already member
                    skippedCount++;
                    skippedData.Add(line);
                }
            }

            // Display results
            this.LiteralSuccessCount.Text = successCount.ToString();
            this.LiteralSkippedCount.Text = skippedCount.ToString();
            this.LiteralErrorCount.Text = errorCount.ToString();
            this.LiteralSkippedData.Text = string.Join(", ", skippedData);
            this.LiteralErrorData.Text = string.Join(", ", errorData);
            this.MultiViewPage.SetActiveView(this.ViewResult);
        }

        private static MailAddress TryParseMailAddress(string s) {
            try {
                return new MailAddress(s);
            }
            catch {
                return null;
            }
        }

    }
}